//
//  PieChartView.m
//  GuBoShi
//
//  Created by 袁斌 on 2017/3/27.
//  Copyright © 2017年 YiShi. All rights reserved.
//

#import "PieChartView.h"

@interface PieChartView ()

@end

@implementation PieChartView

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        
    }
    return self;
}

- (instancetype)initWithCoder:(NSCoder *)aDecoder
{
    self = [super initWithCoder:aDecoder];
    if (self) {
        
    }
    return self;
}


- (void)reloadData
{
    [self initDrawView];
    
    NSArray *values;
    NSArray *colors;
    
    if (_dataSource && [_dataSource respondsToSelector:@selector(pieChartViewAreaDataValues)]) {
        values = [_dataSource pieChartViewAreaDataValues];
    }
    
    if (_dataSource && [_dataSource respondsToSelector:@selector(pieChartViewAreaFillColors)]) {
        colors = [_dataSource pieChartViewAreaFillColors];
    }
    //求和
    float sum = 0;
    for (NSDecimalNumber *number in values) {
        sum += [number doubleValue];
    }

    
    CGPoint sPoint = CGPointMake(self.bounds.size.width / 2.0, self.bounds.size.height / 2.0);
    CGFloat startAngle = 0.0f;
    CGFloat endAngle = 0.0f;
    float r = self.bounds.size.width / 2.0;
    
    for (int i = 0; i < values.count; ++i) {
        
        float percent = [values[i] floatValue] / sum;
        endAngle = startAngle + percent * 2 * M_PI;
        
        CAShapeLayer *layer = [CAShapeLayer layer];
        UIBezierPath *path = [UIBezierPath bezierPathWithArcCenter:sPoint radius:r startAngle:startAngle endAngle:endAngle clockwise:YES];
        [path addLineToPoint:sPoint];
        [path closePath];
        
        UIColor *fillColor = colors[i];
        
        layer.path = path.CGPath;
        layer.fillColor = fillColor.CGColor;
        layer.strokeColor = [UIColor clearColor].CGColor;
        [self.layer addSublayer:layer];
        
        startAngle = endAngle;

    }
    
}

- (void)initDrawView
{
    [self.layer.sublayers makeObjectsPerformSelector:@selector(removeFromSuperlayer)];
}

@end
